﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cn.Edwon.Web.Support;
using Cn.Cellula.Model.Calendar;
using Cn.Edwon.Biz;
using Cn.Edwon.Spring;
using Cn.Cellula.Biz.Port;
using Cn.Edwon.Web.Script;
using System.Text;
using Cn.Cellula.Biz;
using Cn.Edwon.Data;
using System.Data;
using Cn.Cellula.Model.Security;

namespace Cn.Cellula.MiniTopSite.Ws {
    public partial class _Todo : PageSupport {
        ICalendarBiz biz = BizFactory.Get<ICalendarBiz>();
        String _p_Action = "";
        DateTime _p_dt = DateTime.Now;
        String _p_todoKey = "";
        String _p_userKey = "";
        protected void Page_Load(object sender, EventArgs e) {
            try {
                if (!String.IsNullOrEmpty(Request.QueryString["dt"])) {
                    _p_dt = Convert.ToDateTime(Request.QueryString["dt"]);
                }
            } catch {
            }
            _p_userKey = Request.QueryString["uid"];
            _p_todoKey = Request.QueryString["id"];
            _p_Action = Request.QueryString["act"];
            try {
                if (_p_Action == "0") { //进行中的
                    _p_userKey = this.Actor.ID;
                    ResponseOut(LoadTask(_p_dt));
                } else if (_p_Action == "10") {//开始一个任务
                    ResponseOut(StartTask(_p_todoKey));
                } else if (_p_Action == "11") {//结束一个任务
                    ResponseOut(CloseTask(_p_todoKey));
                } else if (_p_Action == "31") {//增加一个任务
                    ResponseOut(AddTask());
                } else if (_p_Action == "32") {//增加一个任务
                    ResponseOut(UpdateTask());
                } else if (_p_Action == "33") {//删除一个任务
                    ResponseOut(DeleteTask());
                } else if (_p_Action == "71") {//月历查看
                    ResponseOut(LoadMonthlyUserTask(_p_dt));
                } else if (_p_Action == "81") {//跟踪项目进度
                    ResponseOut(LoadTrackData(_p_dt));
                } else if (_p_Action == "91") {//查看用户的工作量
                    ResponseOut(LoadUserTaskSum(_p_dt));
                } else if (_p_Action == "99") {//查看所有用户的某月每天的工时数
                    ResponseOut(LoadSuperviseMonthly(_p_dt));
                } else {
                    ResponseOut("[0,\"WebService Error:$nUnkonwn Action:" + _p_Action + "\"]");
                }
            } catch (Exception ex) {
                log.Error(ex.StackTrace);
                ResponseOut("[0,\"Exception:" + ex.Message.Replace("\"","") + "\"]");
            }
        }
        private void ResponseOut(String rContent) {
            Response.Clear();
            Response.Write(rContent);
        }

        private IList<VCalendarTodoEO> loadUserTask(String start,String end,String rOwnerKey,String rUserId) {
            String hql = "from VCalendarTodoEO eo";
            hql += " where eo.OwnerKey='" + rOwnerKey + "' ";
            if (!String.IsNullOrEmpty(_p_userKey)) {
                hql += " and eo.AssignToUser='" + rUserId + "' ";
            }
            hql += " and eo.OccurDt>='" + start + "' ";
            hql += " and eo.OccurDt<='" + end + "' ";
            hql += " order by eo.TodoLevel,eo.StartToReal ";
            return biz.Find<VCalendarTodoEO>(hql);
        }

        #region 动作系列的操作
        private String StartTask(String rTodoKey) {
            try {
                TCalendarTodoEO eo = biz.Load<TCalendarTodoEO>(rTodoKey);
                eo.StartToReal = DateTime.Now;
                if (eo.StartToPlan == null) {
                    eo.StartToPlan = eo.StartToReal;
                }
                biz.Update<TCalendarTodoEO>(eo);
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "[0," + ex.Message.Replace("\"", "\\\"") + "]";
            }
            return "[1,\"执行开始成功\"]";
        }
        private String CloseTask(String rTodoKey) {
            try {
                biz.CloseTodo(rTodoKey, DateTime.Now);
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "[0," + ex.Message.Replace("\"", "\\\"") + "]";
            }
            return "[1,\"执行关闭成功\"]";
        }
        private String AddTask() {
            try {
                TCalendarTodoEO eo = new TCalendarTodoEO();
                eo.Content = Request.QueryString["content"];
                try {
                    eo.CostHours = Convert.ToDecimal(Request.QueryString["cost"]);
                } catch { }
                eo.CreateDt = DateTime.Now;
                eo.IsPrivate = 0;
                eo.LastDt = DateTime.Now;
                eo.Operator = base.Actor.ID;
                eo.OwnerKey = this.OwnerKey;
                try {
                    eo.OccurDt = Convert.ToDateTime(Request.QueryString["occ"]);
                } catch (Exception ex) {
                    eo.OccurDt = DateTime.Now;
                }
                if (biz.IfOccurDtChecked(eo.OccurDt)) {
                    return "[0,\"Add Task Exception:$n" + eo.OccurDt.ToString("yyyy年MM月") + "已结，无法录入该月数据\"]";
                }
                if (!String.IsNullOrEmpty(Request.QueryString["st"])) {
                    try {
                        eo.StartToPlan = eo.StartToReal = Convert.ToDateTime(Request.QueryString["st"]);
                    } catch (Exception ex) {
                        //eo.StartToReal = eo.StartToPlan = Convert.ToDateTime(eo.OccurDt.ToString("yyyy-MM-dd ") + DateTime.Now.ToString("hh:mm:ss"));
                        eo.StartToPlan = eo.StartToReal = null;
                        log.Error("_Todo Exception:load st param:" + ex.Message);
                    }
                } else {
                    eo.StartToPlan = eo.StartToReal = null;
                }
                if (!String.IsNullOrEmpty(Request.QueryString["et"])) {
                    try {
                        eo.EndToPlan = eo.EndToReal = Convert.ToDateTime(Request.QueryString["et"]);
                    } catch (Exception ex) {
                        eo.EndToPlan = eo.EndToReal = null;
                        log.Error("_Todo Exception:load et param:" + ex.Message);
                    }
                } else {
                    eo.EndToPlan = eo.EndToReal = null;
                }
                eo.IfClose = (eo.EndToReal != null) ? 1 : 0;
                eo.TodoLevel = CodeTypeDef.Todolevel.Normal;
                eo.TodoTitle = Request.QueryString["title"];
                eo.TodoType = Request.QueryString["type"];
                eo.RefItemKey = Request.QueryString["item"];
                if (String.IsNullOrEmpty(Request.QueryString["ato"])) {
                    eo.AssignToUser = this.Actor.ID;
                } else {
                    eo.AssignToUser = Request.QueryString["ato"];
                }
                biz.Save<TCalendarTodoEO>(eo);
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "[0,\"Add Task Exception:$n" + ex.Message.Replace("\"", "\\\"") + "\"]";
            }
            return "[1,\"添加成功\"]";
        }
        private String UpdateTask() {
            try {
                TCalendarTodoEO eo = biz.Load<TCalendarTodoEO>(Request.QueryString["id"]);
                if (eo.IsLocked == 1) {
                    return "[0,Update Task Error:$n该内容不允许修改]";
                }
                eo.Content = Request.QueryString["content"];
                try {
                    eo.CostHours = Convert.ToDecimal(Request.QueryString["cost"]);
                } catch { }
                eo.CreateDt = DateTime.Now;
                eo.IsPrivate = 0;
                eo.LastDt = DateTime.Now;
                eo.OwnerKey = this.OwnerKey;
                if (String.IsNullOrEmpty(Request.QueryString["ato"])) {
                    eo.AssignToUser = this.Actor.ID;
                } else {
                    eo.AssignToUser = Request.QueryString["ato"];
                }
                eo.OccurDt = Convert.ToDateTime(Request.QueryString["occ"]).AddHours(9);
                try {
                    if (!String.IsNullOrEmpty(Request.QueryString["st"])) {
                        eo.StartToPlan = eo.StartToReal = Convert.ToDateTime(Request.QueryString["st"]);
                    } else {
                        eo.StartToReal = eo.StartToPlan = Convert.ToDateTime(eo.OccurDt.ToString("yyyy-MM-dd ") + DateTime.Now.ToString("hh:mm:ss"));
                    }
                } catch (Exception ex) {
                    eo.StartToReal = eo.StartToPlan = Convert.ToDateTime(eo.OccurDt.ToString("yyyy-MM-dd ") + DateTime.Now.ToString("hh:mm:ss"));
                    log.Error("_Todo Exception:load st param:" + ex.Message);
                }
                if (!String.IsNullOrEmpty(Request.QueryString["et"])) {
                    try {
                        eo.EndToPlan = eo.EndToReal = Convert.ToDateTime(Request.QueryString["et"]);
                    } catch (Exception ex) {
                        eo.EndToPlan = eo.EndToReal = null;
                        log.Error("_Todo Exception:load et param:" + ex.Message);
                    }
                } else {
                    eo.EndToPlan = eo.EndToReal = null;
                }
                eo.IfClose = (eo.EndToReal != null) ? 1 : 0;
                eo.TodoLevel = CodeTypeDef.Todolevel.Normal;
                eo.TodoTitle = Request.QueryString["title"];
                eo.TodoType = Request.QueryString["type"];
                eo.RefItemKey = Request.QueryString["item"];
                biz.Update<TCalendarTodoEO>(eo);
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "[0,Update Task Exception:$n" + ex.Message.Replace("\"", "\\\"") + "]";
            }
            return "[1,\"更新成功\"]";
        }
        private String DeleteTask() {
            try {
                TCalendarTodoEO eo = biz.Load<TCalendarTodoEO>(Request.QueryString["id"]);
                if (eo.IsLocked == 1) {
                    return "[0,Delete Task Error:$n该内容不允许删除]";
                }
                if (eo.Operator == this.Actor.ID) {
                    biz.Delete<TCalendarTodoEO>(eo);
                } else {
                    return "[0,Delete Task Exception:$n权限不足]";
                }
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "[0,Update Task Exception:$n" + ex.Message.Replace("\"", "\\\"") + "]";
            }
            return "[1,\"删除成功\"]";
        }
        #endregion

        #region 列表系列的操作

        private String LoadTask(DateTime dt) {
            String start = dt.ToString("yyyy-MM-dd") + " 00:00:00";
            String end = dt.ToString("yyyy-MM-dd") + " 23:59:59";
            IList<VCalendarTodoEO> list = loadUserTask(start, end, this.OwnerKey, _p_userKey);
            return JsUtil.ParseEOList2Json(list);
        }

        private String LoadUserTaskSum(DateTime dt) {
            String start = dt.ToString("yyyy-MM-dd") + " 00:00:00";
            String end = dt.ToString("yyyy-MM-dd") + " 23:59:59";
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            Int32 _idx = 0;
            if (!String.IsNullOrEmpty(_p_userKey)) {//查看某个人的
                IList<VCalendarTodoEO> list = loadUserTask(start, end, this.OwnerKey, _p_userKey);
                foreach (VCalendarTodoEO eo in list) {
                    if (_idx > 0)
                        sb.Append(",");
                    sb.Append("{");
                    sb.Append("UserKey:\"\"");
                    sb.Append(",ItemName:\"" + eo.TodoTitle + "\"");
                    sb.Append(",Project:\"" + eo.RefItemName+ "\"");
                    sb.Append(",CostHours:\"" + eo.CostHours + "\"");
                    sb.Append("}");
                    _idx++;
                }
            } else {//所有下属的
                IList<VSysUserEO> list = BizFactory.Get<IUserBiz>().LoadLowerUser(this.Actor.ID, this.Power, false);
                IList<CallingParameter> ps = new List<CallingParameter>();
                ps.Add(new CallingParameter("r_from_dt",start,false));
                ps.Add(new CallingParameter("r_end_dt",end,false));
                ps.Add(new CallingParameter("r_ownerkey",this.Actor.OwnerKey,false));
                ps.Add(new CallingParameter("r_dept_key",this.Power.DeptKey,false));
                ps.Add(new CallingParameter("r_dept_level",this.Power.DeptLevel,true));
                ps.Add(new CallingParameter("r_role_key",this.Power.RoleKey,false));
                ps.Add(new CallingParameter("r_role_level",this.Power.RoleLevel,true));
                DataSet ds = biz.ADOExcuteProc("p_calendar_todo_manhour", ps);
                if (ds != null && ds.Tables.Count > 0) {
                    for(int i=0;i<list.Count;i++){
                        VSysUserEO user = list[i];
                        if (i > 0)
                            sb.Append(",");
                        sb.Append("{");
                        sb.Append("UserKey:\"" + user.UserKey + "\"");
                        sb.Append(",ItemName:\"" + user.UserName + "\"");
                        sb.Append(",Project:\"" + user.Duty + "\"");
                        Boolean find = false;
                        foreach (DataRowView row in ds.Tables[0].DefaultView) {
                            if (row["assign_to_user"]!=null && row["assign_to_user"].ToString() == user.UserKey) {
                                sb.Append(",CostHours:\"" + row["cost_hours"] + "\"");
                                find = true;
                                break;
                            }
                        }
                        if (!find) {
                            sb.Append(",CostHours:\"0\"");
                        }
                        sb.Append("}");
                    }
                } else {
                    for (int i=0;i<list.Count;i++){
                        VSysUserEO user = list[i];
                        if (i > 0)
                            sb.Append(",");
                        sb.Append("{");
                        sb.Append("UserKey:\"\"");
                        sb.Append(",ItemName:\"" + user.UserName + "\"");
                        sb.Append(",Project:\"" + user.Duty + "\"");
                        sb.Append(",CostHours:\"--\"");
                        sb.Append("}");
                    }
                }
            }
            sb.Append("]");
            return sb.ToString();
        }

        private String LoadMonthlyUserTask(DateTime dt) {
            Boolean ischecked = biz.IfOccurDtChecked(dt);
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            if (ischecked) {
                sb.Append("Checked:1");
            } else {
                sb.Append("Checked:0");
            }
            sb.Append(",Data:[");
            IList<CallingParameter> ps = new List<CallingParameter>();
            ps.Add(new CallingParameter("r_user", _p_userKey, false));
            ps.Add(new CallingParameter("r_year", dt.Year, true));
            ps.Add(new CallingParameter("r_month", dt.Month, true));
            DataSet ds = biz.ADOExcuteProc("p_calendar_todo_user_monthly", ps);
            if (ds != null && ds.Tables.Count > 0) {
                int idx = 0;
                foreach (DataRowView row in ds.Tables[0].DefaultView) {
                    if (idx > 0)
                        sb.Append(",");
                    sb.Append("{");
                    sb.Append("TheDay:\"" + row["the_day"] + "\"");
                    if (IsWeekend(dt.Year, dt.Month, row["the_day"].ToString())) {
                        sb.Append(",Weekend:1");
                    } else {
                        sb.Append(",Weekend:0");
                    }
                    sb.Append(",CostHours:\"" + row["cost_hours"] + "\"");
                    sb.Append("}");
                    idx++;
                }
            }
            sb.Append("]}");
            return sb.ToString();
        }
        private Boolean IsWeekend(int year, int month, string day) {
            try {
                DateTime dt = Convert.ToDateTime(year + "-" + month + "-" + day);
                return (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday);
            } catch {
                return false;
            }
        }

        private String LoadTrackData(DateTime dt) {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            IList<CallingParameter> ps = new List<CallingParameter>();
            ps.Add(new CallingParameter("r_item", Request.QueryString["ik"], false));
            ps.Add(new CallingParameter("r_user", base.Actor.ID, false));
            ps.Add(new CallingParameter("r_startdt", Convert.ToDateTime(dt.ToString("yyyy-MM-dd 00:00:00")), false));
            ps.Add(new CallingParameter("r_enddt", Convert.ToDateTime(dt.ToString("yyyy-MM-dd 23:59:59")), false));
            DataSet ds = biz.ADOExcuteProc("p_calendar_todo_by_item", ps);
            if (ds != null && ds.Tables.Count > 0) {
                int idx = 0;
                //vct.todo_key,vct.ref_item_key,vct.ref_item_name,vct.cost_hours,vct.assign_to_user,vct.assign_to_user_name
                //,vct.start_to_plan,vct.start_to_real,vct.end_to_plan,vct.end_to_real
                foreach (DataRowView row in ds.Tables[0].DefaultView) {
                    if (idx > 0)
                        sb.Append(",");
                    sb.Append("{");
                    sb.Append("TodoKey:\"" + row["todo_key"] + "\"");
                    sb.Append(",TodoTitle:\"" + row["todo_title"] + "\"");
                    sb.Append(",CostHours:\"" + row["cost_hours"] + "\"");
                    sb.Append(",UserKey:\"" + row["assign_to_user"] + "\"");
                    sb.Append(",UserName:\"" + row["assign_to_user_name"] + "\"");
                    sb.Append(",StartToPlan:\"" + row["start_to_plan"] + "\"");
                    sb.Append(",StartToReal:\"" + row["start_to_real"] + "\"");
                    sb.Append(",EndToPlan:\"" + row["end_to_plan"] + "\"");
                    sb.Append(",EndToReal:\"" + row["end_to_real"] + "\"");
                    sb.Append(",OccurDt:\"" + row["occur_dt"] + "\"");
                    sb.Append("}");
                    idx++;
                }
            }
            sb.Append("]");
            return sb.ToString();
        }
        public String LoadSuperviseMonthly(DateTime dt) {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            IList<CallingParameter> ps = new List<CallingParameter>();
            ps.Add(new CallingParameter("r_year", dt.Year, true));
            ps.Add(new CallingParameter("r_month",dt.Month, true));
            ps.Add(new CallingParameter("r_operator", this.Actor.ID, false));
            DataSet ds = biz.ADOExcuteProc("p_calendar_supervise_monthly_alluser", ps);
            int daysOfMonth = Convert.ToDateTime(dt.ToString("yyyy-M-1")).AddMonths(1).AddDays(-1).Day;
            if (ds != null && ds.Tables.Count > 0) {
                int idx = 0;
                //vct.todo_key,vct.ref_item_key,vct.ref_item_name,vct.cost_hours,vct.assign_to_user,vct.assign_to_user_name
                //,vct.start_to_plan,vct.start_to_real,vct.end_to_plan,vct.end_to_real
                foreach (DataRowView row in ds.Tables[0].DefaultView) {
                    if (idx > 0)
                        sb.Append(",");
                    sb.Append("[");
                    sb.Append("\"" + row["user_key"] + "\"");
                    sb.Append(",\"" + row["user_name"] + "\"");
                    for (int i = 1; i <= daysOfMonth; i++) {
                        sb.Append("," + row["m"+i] + "");
                    }
                    sb.Append("]");
                    idx++;
                }
            }
            sb.Append("]");
            return sb.ToString();
        }
        #endregion

    }
}